package com.example.Servlet;

import com.example.entity.User;
import com.example.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet({"/getUser","/editUser"})
public class UserServlet extends HttpServlet {
    UserService userService = new UserService();//实例化业务层
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        switch (path){
            case "/getUser"://通过昵称找用户昵称
                getUserByNickName(req, resp);
                break;
            case "/editUser":
                gteUserById(req, resp);
                break;
        }

    }

    private void gteUserById(HttpServletRequest req, HttpServletResponse resp) {
        String user_id = req.getParameter("user_id");
        try {
            User user = userService.getUserById(Integer.valueOf(user_id));
            req.setAttribute("user", user);
            req.getRequestDispatcher("editUser.jsp").forward(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void getUserByNickName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryName = req.getParameter("queryName");//请求获取查询条件
        try {
            List<User> userList = userService.getUserByNickName(queryName);//通过昵称，查询得到用户集合
            req.setAttribute("userList", userList);//将用户集合保存到request作用域中
            req.getRequestDispatcher("ok.jsp").forward(req, resp);//转发到ok.jsp页面
        }catch (SQLException e){
            throw new RuntimeException(e);
        }
    }

}

